import KeyValuePairsDb, { KVPair, OperableStoreShow } from "../logic/database/KeyValuePairsDb";


/**
 * 接口: 数据访问工具
 */
export interface IDataAccess {
    /**
     * 写入内容
     * @param key 键名
     * @param value 内容
     */
    Write<T>(key: string, value: T): Promise<boolean>;

    /**
     * 读取内容
     * @param key 键名
     */
    Read<T>(key: string): Promise<T>;
}

export function GetDataAccess_IOFile(store: OperableStoreShow): IDataAccess {
    return new DataAccess_IOFile(store);
}

class DataAccess_IOFile implements IDataAccess {
    private readonly db: KeyValuePairsDb;
    private readonly store: OperableStoreShow;

    constructor(store: OperableStoreShow) {
        this.store = store;
        this.db = new KeyValuePairsDb();
    }

    async Write<T>(key: string, value: T): Promise<boolean> {
        let self = this;
        if (self.store === null) {
            throw new Error("请先选择存储数据区.");
        }
        let dict:KVPair = {};
        dict[key] = value;

        let result = await self.db.Write(self.store.Name, dict);
        if (result === null) {
            console.error(`API写入数据失败, 返回为空`);
            return false;
        }
        if (result.Code !== 0) {
            console.error(`API写入数据失败: ${result.Message}`);
        }
        return result.Code === 0;
    }

    async Read<T>(key: string): Promise<T> {
        let self = this;
        if (self.store === null) {
            throw new Error("请先选择存储数据区.");
        }
        let result = await self.db.Read(self.store.Name, key);
        if (result === null) {
            console.error(`API写入数据失败, 返回为空`);
        }
        if (result.Code !== 0) {
            console.error(`API写入数据失败: ${result.Message}`);
        }
        let dict = result.Data;
        let value = dict.Get(key);
        return value as T;
    }
}
